package org.bartcr.tools.io.scanner.filter;

import org.bartcr.tools.io.scanner.ClassFilter;

import java.lang.annotation.Annotation;

public class AnnotationFilter implements ClassFilter {

    private final String annotationClassName;
    private final Class<? extends Annotation> annotationClass;

    public AnnotationFilter(String annotationClassName) {
        this.annotationClassName = annotationClassName;
        this.annotationClass = null;
    }

    public AnnotationFilter(Class<? extends Annotation> annotationClass) {
        this.annotationClass = annotationClass;
        this.annotationClassName = null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean accept(Class<?> aClass, ClassLoader loader) {
        Class<? extends Annotation> annotation = annotationClass;
        if (annotation == null) {
            try {
                annotation = (Class<? extends Annotation>) Class.forName(annotationClassName, true, loader);
            } catch (ClassNotFoundException ignore) {
            }
        }

        if (annotation != null) {
            Annotation aClassAnnotation = aClass.getAnnotation(annotation);
            return aClassAnnotation != null;
        }
        return false;
    }
}
